﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using KC.DataAccess.InfoAggregator;

namespace KC.Business
{
	public static class InfoAggregator
	{
		public static TreeNode BuildTree(ref InfoDataContext dc, RssChannel channel)
		{
			TreeNode tn = new TreeNode(channel.Title);
			tn.Tag = channel;

			foreach (RssChannel child in
				from c in dc.RssChannels
				where c.ParentID == channel.ID
				orderby c.ID descending 
				select c)
				tn.Nodes.Add(BuildTree(ref dc, child));
			return tn;
		}
		public static bool AddChannel(ref InfoDataContext dc, string url)
		{
			string result = new System.Net.WebClient().DownloadString(url);
			XmlDocument xDoc = new XmlDocument();
			xDoc.LoadXml(result);
			try
			{
				RssChannel chan = ParseChannel(xDoc);
				chan.RssURL = url;
				dc.RssChannels.InsertOnSubmit(chan);
				dc.SubmitChanges();
				return true;
			}
			catch (Exception ex)
			{
				// TODO: Log error
				return false;
			}

		}
		private static RssChannel ParseChannel(XmlDocument xdoc)
		{
			RssChannel chan = new RssChannel();
			chan.Title = xdoc.SelectSingleNode(@"/rss/channel/title") == null ? "" : xdoc.SelectSingleNode(@"/rss/channel/title").InnerText.Trim();
			chan.ImageURL = xdoc.SelectSingleNode(@"/rss/channel/image/url") == null ? "" : xdoc.SelectSingleNode(@"/rss/channel/image/url").InnerText.Trim();
			chan.Description = xdoc.SelectSingleNode(@"/rss/channel/description") == null ? "" : xdoc.SelectSingleNode(@"/rss/channel/description").InnerText.Trim();
			chan.Link = xdoc.SelectSingleNode(@"/rss/channel/link") == null ? "" : xdoc.SelectSingleNode(@"/rss/channel/link").InnerText.Trim();
			chan.PubDate = xdoc.SelectSingleNode(@"/rss/channel/pubDate") == null ? DateTime.Now : DateTime.Parse(xdoc.SelectSingleNode(@"/rss/channel/pubDate").InnerText.Trim());
			chan.Generator = xdoc.SelectSingleNode(@"/rss/channel/generator") == null ? "" : xdoc.SelectSingleNode(@"/rss/channel/generator").InnerText.Trim();
			return chan;
		}
		public static string DownloadNewItems(ref InfoDataContext dc, RssChannel chan)
		{
			string result = "";
			DateTime dtOldest = DateTime.MinValue;
			var items = from ri in dc.RssItems orderby ri.ID descending select ri;
			if (items.Count() > 0)
				dtOldest = items.First().PubDate;
			result = " Downloading new items from " + chan.Title.Trim() + "...\r\n";
			result += "  Last known post was " + dtOldest.ToString("MM/dd/yy HH:mm:ss") + "\r\n";

			// Download the item feed; Find and parse individual RssItems
			string xml = new System.Net.WebClient().DownloadString(chan.RssURL);
			XmlDocument xdoc = new XmlDocument();
			xdoc.LoadXml(xml);

			// Loop through items in this channel and insert them
			XmlNodeList nodes = xdoc.SelectNodes(@"/rss/channel/item");
			result += "  " + nodes.Count.ToString() + " nodes downloaded from " + chan.RssURL + " \r\n";
			int ItemsDownloaded = 0;
			foreach (XmlNode node in nodes)
			{	
				if (node.Name.ToLower() != "item")
					continue;
				RssItem item = ParseItem(node);
				item.ChannelID = chan.ID;
				if ((from ri in dc.RssItems where ri.URL == item.URL select ri).Count() == 0)
				{
					dc.RssItems.InsertOnSubmit(item);
					ItemsDownloaded++;
				}
			}
			dc.SubmitChanges();
			result += "  " + ItemsDownloaded.ToString() + " of " + nodes.Count.ToString() + " inserted.\r\n";
			return result;
		}
		private static RssItem ParseItem(XmlNode node)
		{
			RssItem item = new RssItem();
			if (node.SelectSingleNode(@"title") == null)
				return null;

			item.Title = node.SelectSingleNode(@"title") == null ? "" : node.SelectSingleNode(@"title").InnerText.Trim();
			item.Description = node.SelectSingleNode(@"description") == null ? "" : node.SelectSingleNode(@"description").InnerText.Trim().Replace("<![CDATA[", "").Replace("]]>", "");
			item.CommentsURL = node.SelectSingleNode(@"comments") == null ? "" : node.SelectSingleNode(@"comments").InnerText.Trim();
			item.URL = node.SelectSingleNode(@"link") == null ? "" : node.SelectSingleNode(@"link").InnerText.Trim();
			DateTime pubDate = DateTime.Now;
			if (node.SelectSingleNode(@"pubDate") != null)
				DateTime.TryParse(node.SelectSingleNode(@"pubDate").InnerText.Trim(), out pubDate);
			if (pubDate < DateTime.Parse("01/01/2000"))
				pubDate = DateTime.Now;
			item.PubDate = pubDate;
			return item;
		}
		public static string FormatLiveTextStream(List<RssItem> items)
		{
			string live = "";
			foreach (RssItem ri in items)
				live += System.Text.RegularExpressions.Regex.Replace(ri.Description, @"<.*?>", "\r\n\r\n").Trim().Replace('\t', ' ') + "\r\n\r\n";
			while (live.Contains("  "))
				live = live.Replace("  ", " ");
			while (live.Contains("\r\n\r\n\r\n"))
				live = live.Replace("\r\n\r\n\r\n", "\r\n\r\n");

			return live;
		}

	}
}
